using System;
using System.Linq;
using AutoPoco.Engine;

namespace Autopoco.Contrib.DataSources
{
    public class RelationalDataSource<TSource, T> : DatasourceBase<T> where TSource : DatasourceBase<T>, IRelatedDataSource
    {
        private readonly TSource _source;
        private readonly RelationContext _context;

        public RelationalDataSource(RelationContext context, int level)
        {
            _context = context;
            _source = Activator.CreateInstance(typeof(TSource)) as TSource;
            if (!_context.Dictionary.ContainsKey(level))
                _context.Dictionary.Add(level, _source);

        }

        public override T Next(IGenerationSession session)
        {
            var t = _source.Next(session);
            var dataSources = _context.Dictionary.Values.OfType<IRelatedDataSource>().ToList();
            foreach (var item in dataSources)
            {
                item.Setup(_context);
            }
            return t;
        }
    }
}